package com.sy.core.website;

import com.sy.core.model.SysUser;
import com.sy.core.util.*;
import com.sy.core.web.BaseCtl;
import io.netty.util.ByteProcessor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 用户注册模块
 */
@Controller
@RequestMapping("register")
public class RegisterCtl extends BaseCtl {

    /**
     * 网站用户注册接口
     * @param user
     * @return
     */
    @RequestMapping("save")
    @ResponseBody
    public RestResult register(SysUser user, String code, String phone,String password1,String password2){
        if (StringUtils.isNotBlank(code)) {
            String code2 = (String) request.getSession().getAttribute(
                    "validationCode");
            String phone2 = (String) request.getSession().getAttribute(
                    "telephone");

            if (code.equalsIgnoreCase(code2)&&phone2.equalsIgnoreCase(phone)) {
                String uRex = "^[a-zA-Z0-9_-]{2,16}$";
                String pRex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
                if(!password1.equalsIgnoreCase(password2)) return new RestResult(false,"注册密码不一致");
                if (password1.matches(pRex)) {
                    try{
                        if(StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(password1)){
                            user.setPk(BaseUUID.getUUID());
                            user.setPhone(phone);
                            user.setPassword(MD5Util.generate(password1,"website"));
                            user.setSalt("website");
                            sysUserService.insert(user);
                            return  new RestResult(true,"注册成功");
                        }else{
                            return  new RestResult(false,"参数异常,手机号或密码不允许为空");
                        }
                    }catch (Exception e){
                        if(e instanceof DuplicateKeyException){
                            if(e.getCause().toString().contains("account")){
                                return new RestResult(false,"用户账号信息已存在,请重新设置");
                            }
                            if(e.getCause().toString().contains("phone")){
                                return new RestResult(false,"手机号码已存在,请直接登录");
                            }
                        }
                        logger.error("新增|修改用户信息异常:"+e.getMessage());
                    }
                    return  new RestResult(false,"注册失败,信息异常");
                } else {
                    return new RestResult(false, "密码强度不符合要求");
                }
            }
            return new RestResult(false, "验证码或手机号码错误");
        } else {
            return new RestResult(false, "验证码已过期");
        }
    }

    /**
     * 获取手机验证码 All rights Reserved, Designed By Chong.CaiXin
     *
     * @Description: TODO(用一句话描述该文件做什么)
     * @author: Chong.CaiXin
     * @date: 2018年6月28日 下午1:38:29
     * @version V1.0
     *
     */
    @RequestMapping("getVerificationCode")
    @ResponseBody
    public RestResult getVerification2Code(String telephone, HttpServletRequest request) {
        RestResult obj;
        if (StringUtils.isNotBlank(telephone)&& telephone.matches(SysConst.PHONE)) {
            Map<String,Object> par = new HashMap<>();
            par.put("phone",telephone);
            SysUser sysUser = sysUserService.queryUserByPhone(par);
            if(sysUser!=null) return new RestResult(false,"此号码已经被注册");
            obj = getVerificationCode(telephone, request);

        } else {
            obj = new RestResult(false, "手机号码格式错误!");
        }
        return obj;
    }
    /**
     * 获取验证码--生成验证码 返回jsessionID
     *
     * @Description:
     * @Title: getVerificationCode
     * @author Chong.caixin
     * @date 2018年3月20日
     * @version V1.0
     */

    public static RestResult getVerificationCode(String telephone,
                                                 HttpServletRequest request) {
        RestResult obj;
        HttpSession session = request.getSession();
        String sessionID = session.getId();
        if (telephone.matches(SysConst.PHONE)) {
            String num = SysConst.getRandNum(6);
            session.setAttribute("validationCode", num);
            session.setAttribute("telephone",telephone);
            System.out.println("验证码:>>>>>>>>>>>>>>>>>>>>>>>:"+num);
            try {
                String str = sendMsg(telephone, num);//发送验证码到用户手机
                //System.err.println(str);
                if(!str.equalsIgnoreCase("108")){
                    obj = new RestResult(true, "验证码发送成功", sessionID);
                }else {
                    obj = new RestResult(false, "验证码发送失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                obj = new RestResult(false, "验证码发送失败!", sessionID);
            }
        } else {
            obj = new RestResult(false, "手机号格式有误!", sessionID);
        }
        return obj;
    }
    /**
     * 手机获取验证码--调用第三方接口
     *
     * @param phoneNumber
     * @param verifyCode
     * @return
     */
    @SuppressWarnings("static-access")
    public static String sendMsg(String phoneNumber, String verifyCode) throws UnsupportedEncodingException {
        HashMap<String, String> hm = new HashMap<String, String>();
        PropertiesUtils prop = new PropertiesUtils();
        Properties props = prop.getProperties("message.properties");
        hm.put("account", props.getProperty("account"));
        hm.put("pswd", props.getProperty("password"));
        hm.put("mobile", phoneNumber);
        hm.put("msg",props.getProperty("message")+verifyCode);
        hm.put("needstatus",props.getProperty("needstatus"));
        hm.put("product",props.getProperty("product"));
        String strMsg = new HttpUtils().sendPost(
                props.getProperty("appcalitionurl"), hm);
        System.out.println(strMsg);
        return strMsg.substring(strMsg.lastIndexOf(",")+1);
    }
    /**
     * 验证码校验
     *
     * @Description:
     * @Title: checkValidationCode
     * @author Chong.caixin
     * @date 2018年3月20日
     * @version V1.0
     */
    @RequestMapping("/checkValidationCode")
    @ResponseBody
    public RestResult checkValidationCode(HttpServletRequest request, String code) {
        RestResult obj = null;
        HttpSession ss = request.getSession();
        if (StringUtils.isNotBlank(code)) {
            String validCode = (String) ss.getAttribute("validationCode");
            if (code.equalsIgnoreCase(validCode)) {
                obj = new RestResult(true, "验证码匹配成功");
            } else {
                obj = new RestResult(false, "验证码匹配失败");
            }
        } else {
            obj = new RestResult(false, "验证码不能为空");
        }
        return obj;
    }

}
